package band.wukong.practice.springboot.spring4.mvc;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author wukong(wukonggg@139.com)
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping({"", "/toUpload"})
    public String index() {
        return "upload";
    }


    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody String upload(MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return "error. empty file.  ";
        }
        try {
            FileUtils.writeByteArrayToFile(new File("d:/" +  file.getOriginalFilename()), file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
        return "ok";
        /*
        String filePath = request.getSession().getServletContext().getRealPath("/") + "\\fileUpload\\" +  file.getOriginalFilename();//感觉是不是对文件名裁剪空格后保存比较好？
        //转存文件
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
         */
    }
}
